package learn;

public class 哲学家 extends Thread {
	private static int[] chopsticks = { 1, 1, 1, 1, 1 };
	private int id;

	public 哲学家(int id) {
		this.id = id;
	}

	@Override
	public void run() {
		for (int i = 0; i < 5; i++) {
			this.eat();
			this.think();
		}
	}

	public void think() {
		// 左筷子放下
		this.chopsticks[this.id] = 1;
		// 右筷子放下
		this.chopsticks[(this.id + 1) % this.chopsticks.length] = 1;
		System.out.println("哲学家_" + this.id + "正在思考");
		// 思考一秒时间
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void eat() {
		if (this.chopsticks[this.id] == 1 && this.chopsticks[(this.id + 1) % this.chopsticks.length] == 1) {
			chopsticks[this.id] = 0;
			System.out.println("哲学家_" + this.id + "拿起了左筷子");
			chopsticks[(this.id + 1) % this.chopsticks.length] = 0;
			System.out.println("哲学家_" + this.id + "拿起了右筷子");
		} else {
			try {
				this.sleep(1000);
				// this.wait(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("哲学家_" + this.id + "的左筷子正在被哲学家_"
					+ ((this.id - 1 + this.chopsticks.length) % this.chopsticks.length) + "使用,等待1000ms");
			System.out.println(
					"哲学家_" + this.id + "的右筷子正在被哲学家_" + ((this.id + 1) % this.chopsticks.length) + "使用,等待1000ms");
		}
		// // 拿起左筷子
		// while (true) {
		// if (this.chopsticks[this.id] != 0) {
		// chopsticks[this.id] = 0;
		// System.out.println("哲学家_" + this.id + "拿起了左筷子");
		// break;
		// } else {
		// try {
		// this.wait(1000);
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// } finally {
		// System.out.println("哲学家_" + this.id + "的左筷子正在被哲学家_"
		// + ((this.id - 1 + this.chopsticks.length) % this.chopsticks.length) +
		// "使用,等待1000ms");
		//
		// }
		// }
		// }
		//
		// // 拿起右筷子
		// while (true) {
		// if (this.chopsticks[(this.id + 1) % this.chopsticks.length] != 0) {
		// chopsticks[(this.id + 1) % this.chopsticks.length] = 0;
		// System.out.println("哲学家_" + this.id + "拿起了右筷子");
		// break;
		// } else {
		// try {
		// this.wait();
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// } finally {
		// System.out.println("哲学家_" + this.id + "的右筷子正在被哲学家_" + ((this.id + 1)
		// % this.chopsticks.length)
		// + "使用,等待1000ms");
		// }
		// }
		// }
		System.out.println("哲学家_" + this.id + "正在吃饭");

		// 吃饭花一秒时间
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// this.notify();
	}

	public static void main(String[] args) {
		new 哲学家(0).start();
		new 哲学家(1).start();
		new 哲学家(2).start();
		new 哲学家(3).start();
		new 哲学家(4).start();
	}
}
